package cn.yunbamboos.db.sql;

import cn.hutool.core.util.StrUtil;
import cn.yunbamboos.db.metadata.ColumnMetadata;
import cn.yunbamboos.db.metadata.TableMetadata;

import java.util.ArrayList;
import java.util.List;

public class GenerateMySQLSql extends GenerateSql {

    public GenerateMySQLSql(TableMetadata tableMetadata) {
        super(tableMetadata);
    }

    public String toCreateTableSql() {
        String DB_NAME = System.getProperty("DB_NAME");
        String tableName = this.tableMetadata.getName();
        List<ColumnMetadata> columns = this.tableMetadata.getColumns();

        StringBuilder builder = new StringBuilder();
        builder.append(StrUtil.format("create table `{}`.`{}`(", DB_NAME, tableName)).append(LINE_BREAK);

        List<String> pks = new ArrayList<>();
        for (ColumnMetadata column : columns) {
            builder.append(SPACE).append(SPACE).append(BACKQUOTE).append(column.getName()).append(BACKQUOTE).append(SPACE);
            switch (column.getType()) {
                case String -> {
                    // `user_id` bigint NOT NULL COMMENT '用户ID',
                    builder.append("varchar").append(LEFT_BRACKET).append(column.getLength()).append(RIGHT_BRACKET);
                }
                case Integer -> {
                    builder.append("int");
                }
                case Long -> {
                    builder.append("bigint");
                }
                case Boolean -> {
                    builder.append("boolean");
                }
                case DateTime -> {
                    builder.append("varchar").append(LEFT_BRACKET).append(19).append(RIGHT_BRACKET);
                }
                case Mediumtext -> {
                    builder.append("mediumtext");
                }
            }
            if (column.isPrimaryKey()) {
                builder.append(SPACE).append("not null").append(SPACE);
            }
            builder.append(COMMA).append(LINE_BREAK);

            if (column.isPrimaryKey()) {
                pks.add(BACKQUOTE + column.getName() + BACKQUOTE);
            }
        }

        builder.append(SPACE).append(SPACE).append("primary key (").append(StrUtil.join(",", pks)).append(")").append(LINE_BREAK);

        builder.append(")").append(LINE_BREAK);
        return builder.toString();
    }

}
